package com.usian.security.config;

import com.usian.security.filter.JwtAuthenticationTokenFilter;
import com.usian.security.handler.AuthenticationEntryPointHandler;
import com.usian.security.handler.CustomAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    token过滤的filter
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
//    认证异常
    @Autowired
    private AuthenticationEntryPointHandler authenticationEntryPointHandler;
//    授权异常处理
    @Autowired
    private CustomAccessDeniedHandler customAccessDenieHandler;
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
//                关闭csrf功能
        .csrf().disable()
//            不通过session获取securityContext
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
//                允许匿名访问  登录后不能访问
                .antMatchers("/user/login").anonymous()
//                除了上面的路径，其他都需要鉴权访问
                .anyRequest().authenticated();

//        添加过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

//        异常处理
        http
                .exceptionHandling()
//                认证异常处理器
        .authenticationEntryPoint(authenticationEntryPointHandler)
//                授权异常处理器
        .accessDeniedHandler(customAccessDenieHandler);
//        添加跨域处理
        http.cors();
    }
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean()throws Exception{
        return super.authenticationManagerBean();
    }

}
